/*
	The MIT License

	Copyright (c) 2010 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/

#include "im_local.h"
#include "FreeImage.h"


/*-----------------------------------------------------------------------------
	Export stuff :
-----------------------------------------------------------------------------*/

EImageFactory	static_im;

IImageFactory*	ImageFactory( void )
{
	return &static_im;
}

/*-----------------------------------------------------------------------------
	Main stuff :
-----------------------------------------------------------------------------*/

//
//	EImageFactory::EImageFactory
//
EImageFactory::EImageFactory()
{
	FreeImage_Initialise();
}


//
//	EImageFactory::~EImageFactory
//
EImageFactory::~EImageFactory()
{
	FreeImage_DeInitialise();
}


//
//	EImageFactory::CreateImage
//
IPxImage EImageFactory::CreateImage ( uint w, uint h, const EColor &fill_color )
{
	return new EImage(w, h, fill_color);
}


//
//	EImageFactory::LoadImageFromFile
//
IPxImage EImageFactory::LoadImageFromFile( const EString &path )
{
	for (uint i=0; i<img_list.size(); i++) {
		if (img_list[i].name==path) {
			return img_list[i].image;
		}
	}

	IPxImage	px_img	= new EImage();
	EImage		*img	= px_img.to<EImage>();


	IHrFile f = fs()->openFile(path.CStr(), FS_OPEN_READ);
	if (!f) {
		RUNTIME_ERROR(va("File not found: %s", path.CStr()));
	}

	IPxBlob b = f->binaryBlob();

	//image format
	FREE_IMAGE_FORMAT free_img_format = FIF_UNKNOWN;

	//pointer to the image, once loaded
	FIBITMAP *dib(0);
	FIMEMORY *mem_img = FreeImage_OpenMemory(static_cast<BYTE*>(b->GetBufferPointer()), b->GetBufferSize());

	//check the file signature and deduce its format
	FREE_IMAGE_FORMAT fif = FreeImage_GetFileTypeFromMemory(mem_img, 0);

	//if still unknown, try to guess the file format from the file extension
	if(free_img_format == FIF_UNKNOWN) {
		free_img_format = FreeImage_GetFIFFromFilename(path.CStr());
	}

	//if still unknown, throw exception
	if(free_img_format == FIF_UNKNOWN) {
		FreeImage_CloseMemory(mem_img);
		RUNTIME_ERROR( va("Image: %s - can't be loaded, image format unknown", path.CStr()) );
	}

	if (free_img_format == FIF_TARGA) {
		img->CreateImageFromTGA(b);
	}
	else {

		//check that the plugin has reading capabilities and load the file
		if(FreeImage_FIFSupportsReading(free_img_format)) {
			dib = FreeImage_LoadFromMemory(free_img_format, mem_img);
		}
		//if the image failed to load, throw exception
		if(!dib) {
			FreeImage_CloseMemory(mem_img);
			RUNTIME_ERROR( va("Image: %s - can't be loaded, load fail", path.CStr()) );
		}

		//get the image width and height
		uint width	= FreeImage_GetWidth(dib);
		uint height	= FreeImage_GetHeight(dib);
		uint bpp	= FreeImage_GetBPP(dib);

		byte *bits = FreeImage_GetBits(dib);

		//if this somehow one of these failed, throw exception
		if((bits == 0) || (width == 0) || (height == 0)) {
			FreeImage_Unload(dib);
			FreeImage_CloseMemory(mem_img);
			RUNTIME_ERROR( va("Image: %s - can't be loaded : %d, %d, %d", path.CStr(), bits, width, height) );
		}

		img->CreateImageFromBytes(width, height, bpp, bits);

		//Free FreeImage's copy of the data
		FreeImage_Unload(dib);
	}

	FreeImage_CloseMemory(mem_img);

	images_s image;

	image.name  = path;
	image.image = px_img;

	img_list.push_back(image);

	return px_img;
}


//
//	EImageFactory::SaveImageToFile
//
void EImageFactory::SaveImageToFile( const EString &path, uint image_format, uint w, uint h, uint bpp, void* data )
{

	FREE_IMAGE_FORMAT	fif_format;
	int					flag = 0;

	switch (image_format)
	{
	case 1:
		{
			fif_format	= FIF_PNG;
			flag		= PNG_Z_NO_COMPRESSION;
			//path	   += ".png";
			break;
		}
	case 2:
		{
			fif_format	= FIF_TARGA;
			flag		= TARGA_DEFAULT;
			//path	   += ".tga";
			break;
		}
	case 0:
	default:
		{
			fif_format	= FIF_JPEG;
			flag		= JPEG_QUALITYSUPERB;
			//path	   += ".jpg";
			break;
		}
	}

	FIBITMAP *bitmap = FreeImage_Allocate(w, h, bpp);

	if (!bitmap) {
		RUNTIME_ERROR("FreeImage can't allocate memory for image");
	}

	byte *bits = FreeImage_GetBits(bitmap);

	memcpy(bits, data, w*h*(bpp/8));

	// Save image to file
	FreeImage_Save(fif_format, bitmap, path.CStr(), flag); 

	// Free allocated memory
	FreeImage_Unload(bitmap);
}
